package com.zhan.ielts.web.controller;

import com.zhan.frame.core.dao.BaseService;
import com.zhan.frame.core.web.controller.BaseControllerImpl;
import com.zhan.frame.core.web.domain.Result;
import com.zhan.frame.core.web.domain.Result.Status;
import com.zhan.ielts.domain.ParagraphWord;
import com.zhan.ielts.domain.WordScene;
import com.zhan.ielts.domain.query.ParagraphWordQuery;
import com.zhan.ielts.domain.vo.ParagraphWordVo;
import com.zhan.ielts.domain.word.Dictionary;
import com.zhan.ielts.service.ParagraphService;
import com.zhan.ielts.service.ParagraphWordService;
import com.zhan.ielts.service.word.DictionaryService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/paragraph/word")
public class ParagraphWordController extends BaseControllerImpl<ParagraphWord, ParagraphWordQuery> {

	private Logger log = LoggerFactory.getLogger(ParagraphWordController.class);

	@Autowired
	private ParagraphService paragraphService;

	@Autowired
	private ParagraphWordService paragraphWordService;

	@Autowired
	private DictionaryService dictionaryService;

	@Override
	protected BaseService<ParagraphWord> getBaseService() {
		return paragraphWordService;
	}

	@Override
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView selectList(ParagraphWordQuery query, @PageableDefault Pageable pageable) {
		Page<ParagraphWordVo> page = paragraphWordService.queryPageListCustom(query, pageable);
		ModelAndView mav = new ModelAndView(path.getListViewPath(), "page", page);
		mav.addObject("query", query);
		return mav;
	}

	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String updateParagraph(@RequestParam(value = "file", required = false) MultipartFile file) {
		log.debug("文章更新开始！");
		try {
			boolean flag = true;
			if (file.isEmpty()) {
				return "article zip file can not be null.";
			} else {
				flag = paragraphService.handleParagraph(file);
				if (!flag) {
					return "fail to update article!";
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统错误！");
			return "system error!";
		}
		log.debug("文章更新结束！");

		return "success!";
	}

	@ResponseBody
	@RequestMapping(value = "/addWord", method = RequestMethod.POST)
	public String addWord(ParagraphWord paragraphWord) {
		log.debug("文章更新开始！");
		try {
			boolean flag = true;
			if (StringUtils.isEmpty(paragraphWord.getParagraphId())) {
				return "paragraphId can not be null.";
			} else if (StringUtils.isEmpty(paragraphWord.getWord())) {
				return "word can not be null.";
			}

			paragraphWord.setWord(paragraphWord.getWord().trim());
			Map<String, String> map = paragraphService.getParaphrase(paragraphWord.getParagraphId(),
					paragraphWord.getWord());
			paragraphWord.setParaphrase(map.get("paraphrase"));
			paragraphWord.setTranslation(map.get("paraphraseCn"));
			paragraphWord.setSeqNo(1);
			paragraphWord.setUpdateTime(System.currentTimeMillis());
			paragraphWordService.insert(paragraphWord);

		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统错误！");
			return "system error!";
		}
		log.debug("文章更新结束！");

		return "success!";
	}

	@ResponseBody
	@RequestMapping(value = "/addSubject", method = RequestMethod.POST)
	public ModelAndView addSubject(String word, String subject, String category, String paragraphId,
			String translation, String page, String categoryQuery, String subjectQuery, String wordQuery) {
		log.debug("更新科目开始！");
		try {
			boolean flag = true;
			if (StringUtils.isEmpty(word)) {
				// return "word can not be null.";
			} else if (StringUtils.isEmpty(subject)) {
				// return "subject can not be null.";
			} else if (StringUtils.isEmpty(category)) {
				// return "category can not be null.";
			}

			paragraphWordService.saveScene(word, subject, category, paragraphId, translation);

		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统错误！");
			// return "system error!";
		}
		log.debug("更新科目结束！");

		// return new ModelAndView(path.getRedirectListPath());
		if (categoryQuery != null && categoryQuery.equals("0"))
			categoryQuery = "";
		if (subjectQuery != null && subjectQuery.equals("0"))
			subjectQuery = "";
		if (wordQuery != null && wordQuery.equals("0"))
			wordQuery = "";
		// String redirectPath =
		// path.getRedirectListPath()+"?page="+page+"&category="+categoryQuery+"&subject="+subjectQuery;
		String redirectPath = path.getRedirectListPath() + "?page=" + page + "&word=" + wordQuery;
		return new ModelAndView(redirectPath);

	}

	@ResponseBody
	@RequestMapping(value = "/addToeflCategory", method = RequestMethod.POST)
	public String addToeflCategory() {
		log.debug("更新托福开始！");
		try {
			List<ParagraphWord> paragraphWordList = paragraphWordService.queryAll();
			if (paragraphWordList != null) {
				for (int i = 0; i < paragraphWordList.size(); i++) {
					ParagraphWord tempParagraphWord = paragraphWordList.get(i);
					paragraphWordService.importLevel(tempParagraphWord.getWord(), "托福");
				}
			}

			// paragraphWordService.saveSubject(word, subject, category,
			// paragraphId, translation);

		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统错误！");
			return "system error!";
		}
		log.debug("更新托福结束！");

		return "success";
	}

	@ResponseBody
	@RequestMapping(value = "/importDictionaryLevel", method = RequestMethod.POST)
	public String importDictionaryLevel() {
		log.debug("导入字典level开始！");
		try {
			List<ParagraphWord> paragraphWordList = paragraphWordService.queryAll();
			if (paragraphWordList != null) {
				for (int i = 0; i < paragraphWordList.size(); i++) {
					String word = paragraphWordList.get(i).getWord();
					Dictionary dictionaryQuery = new Dictionary();
					dictionaryQuery.setWord(word);
					Dictionary dictionary = dictionaryService.queryOne(dictionaryQuery);
					if (dictionary != null) {
						String level = dictionary.getLevel();
						if (StringUtils.isNotEmpty(level)) {
							paragraphWordService.importLevel(word, level);
						}
					}

				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统错误！");
			return "system error!";
		}
		log.debug("导入字典level结束！");

		return "success";
	}

	@ResponseBody
	@RequestMapping(value = "/importDictionaryTranslation", method = RequestMethod.POST)
	public String importDictionaryTranslation() {
		log.debug("导入字典翻译开始！");
		try {
			List<ParagraphWord> paragraphWordList = paragraphWordService.queryAll();
			if (paragraphWordList != null) {
				for (int i = 0; i < paragraphWordList.size(); i++) {
					String word = paragraphWordList.get(i).getWord();
					Dictionary dictionaryQuery = new Dictionary();
					dictionaryQuery.setWord(word);
					Dictionary dictionary = dictionaryService.queryOne(dictionaryQuery);
					if (dictionary != null) {
						String translation = dictionary.getTrans();
						String wordClass = dictionary.getWordClass();

						// net.sf.json.JSONObject translationJsonObject =
						// net.sf.json.JSONObject.fromObject(translation);
						// net.sf.json.JSONObject wordClassJsonObject =
						// net.sf.json.JSONObject.fromObject(wordClass);

						if (StringUtils.isNotEmpty(translation)) {
							// paragraphWordService.importTranslation(word,
							// translationJsonObject.getJSONArray("normal").toString(),
							// wordClassJsonObject.getString("normal") );
							paragraphWordService.importTranslation(word, translation, wordClass);
						}

					}

				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统错误！");
			return "system error!";
		}
		log.debug("导入字典翻译结束！");

		return "success";
	}

	@ResponseBody
	@RequestMapping(value = "/updateWordCategory", method = RequestMethod.POST)
	public Result updateWordCategory(@RequestParam(value = "singleFile", required = false) MultipartFile singleFile,
			String yunPath) throws IOException {
		log.debug("上传文件开始！");

		boolean flag = true;

		// 上传文件
		if (!singleFile.isEmpty()) {
			paragraphWordService.updateWordCategory(singleFile);
		}

		log.debug("上传文件开始！");

		return null;

	}

	@ResponseBody
	@RequestMapping(value = "/updateWordSeqNoBatch", method = RequestMethod.POST)
	public String updateWordSeqNoBatch() {
		log.debug("导入字典翻译开始！");
		try {
			paragraphWordService.updateWordSeqNoBatch();

		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统错误！");
			return "system error!";
		}
		log.debug("导入字典翻译结束！");

		return "success";
	}

	@ResponseBody
	@RequestMapping(value = "/updateWordSeqNoBatchRaw", method = RequestMethod.POST)
	public String updateWordSeqNoBatchRaw() {
		log.debug("导入字典翻译开始！");
		try {
			paragraphWordService.updateWordSeqNoBatchRaw();

		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统错误！");
			return "system error!";
		}
		log.debug("导入字典翻译结束！");

		return "success";
	}

	@ResponseBody
	@RequestMapping(value = "/highLightFix", method = RequestMethod.POST)
	public String highLightFix() {
		log.debug("导入字典翻译开始！");
		try {
			paragraphWordService.highLightFix();

		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统错误！");
			return "system error!";
		}
		log.debug("导入字典翻译结束！");

		return "success";
	}

	@SuppressWarnings({ "rawtypes" })
	@RequestMapping(value = "/editSubject/{word}/{page}/{wordQuary}/{categoryQuery}/{subjectQuery}", method = RequestMethod.GET)
	public ModelAndView editSubjectView(@PathVariable("word") String word, @PathVariable("page") String page,
			@PathVariable("wordQuary") String wordQuary, @PathVariable("categoryQuery") String categoryQuery,
			@PathVariable("subjectQuery") String subjectQuery) {
		
		List list = paragraphWordService.getEditSceneView(word, page, wordQuary, categoryQuery, subjectQuery);
		
		return new ModelAndView("paragraph/word/editSubject", "subject", list);
	}

	@ResponseBody
	@RequestMapping(value = "/queryWordCount", method = RequestMethod.POST)
	public String queryWordCount(ParagraphWordQuery paragraphWord) {
		log.debug("查询指定单词数量开始！");
		try {
			boolean flag = true;
			if (StringUtils.isEmpty(paragraphWord.getParagraphId())) {
				return "paragraphId can not be null.";
			} else if (StringUtils.isEmpty(paragraphWord.getWord())) {
				return "word can not be null.";
			}

			Long count = paragraphWordService.queryWordCount(paragraphWord);
			if (count > 0) {
				return "the word exist yet";
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统错误！");
			return "system error!";
		}
		log.debug("查询指定单词数量结束！");

		return "success!";
	}

	// ************************生词新的sentence word*******************************
	@ResponseBody
	@RequestMapping(value = "/handleSentenceWord", method = RequestMethod.POST)
	public Result handleSentenceWord() {
		try {
			paragraphWordService.handleSentenceWord();
		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统错误！");
			return new Result(Status.ERROR, "系统错误");
		}

		return new Result(Status.OK, "");
	}

	// ************************上传四级词汇*****************************************
	@ResponseBody
	@RequestMapping(value = "/uploadCET4Word", method = RequestMethod.POST)
	public Result uploadCET4Word(@RequestParam(value = "singleFile", required = false) MultipartFile singleFile) {
		try {
			// 上传文件
			if (!singleFile.isEmpty()) {
				paragraphWordService.uploadCET4Word(singleFile);
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统错误！");
			return new Result(Status.ERROR, "系统错误");
		}

		return new Result(Status.OK, "");
	}

	// ************************上传补充托福词汇*****************************************
	@ResponseBody
	@RequestMapping(value = "/uploadExToeflWord", method = RequestMethod.POST)
	public Result uploadExToeflWord(@RequestParam(value = "singleFile", required = false) MultipartFile singleFile) {
		try {
			// 上传文件
			if (!singleFile.isEmpty()) {
				paragraphWordService.uploadExToeflWord(singleFile);
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统错误！");
			return new Result(Status.ERROR, "系统错误");
		}

		return new Result(Status.OK, "");
	}

	// ************************上传cet6词汇*****************************************
	@ResponseBody
	@RequestMapping(value = "/uploadCET6Word", method = RequestMethod.POST)
	public Result uploadCET6Word(@RequestParam(value = "singleFile", required = false) MultipartFile singleFile) {
		try {
			// 上传文件
			if (!singleFile.isEmpty()) {
				paragraphWordService.uploadCET6Word(singleFile);
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统错误！");
			return new Result(Status.ERROR, "系统错误");
		}

		return new Result(Status.OK, "");
	}

	// ************************修改subject中指定的句子*****************************************
	@ResponseBody
	@RequestMapping(value = "/updateSubjectSentence", method = RequestMethod.POST)
	public String updateSubjectSentence(WordScene wordSubject) {
		try {
			/*// 上传文件
			if (StringUtils.isEmpty(wordSubject.getWord())) {
				return "word不能为空";
			} else if (StringUtils.isEmpty(wordSubject.getScene1())) {
				return "subject不能为空";
			} else if (StringUtils.isEmpty(wordSubject.getSentenceId())) {
				return "SentenceId不能为空";
			}

			paragraphWordService.saveScene(wordSubject.getWord(), wordSubject.getScene1(), null,
					wordSubject.getSentenceId(), null);*/
		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统错误！");
			return "系统错误";
		}

		return "更新成功";
	}

	// ************************修改word ielts 中的exam Type*****************************************
	@ResponseBody
	@RequestMapping(value = "/updateWordIeltsExamType", method = RequestMethod.POST)
	public String updateWordIeltsExamType(@RequestParam(value = "singleFile", required = false) MultipartFile singleFile) {
		try {

			String filepath = "";
			paragraphWordService.updateWordIeltsExamType(filepath);
		} catch (Exception e) {
			e.printStackTrace();
			log.debug("系统错误！");
			return "系统错误";
		}

		return "更新成功";
	}

	
}
